#include "photo.h"

Photo::Photo(QWidget *parent) : QWidget(parent)
{
    setAttribute(Qt::WA_DeleteOnClose);//关闭时回收内存
#if 1
    loading = new Loading(this);
    loading->setGeometry((1024 - 300)/2, (600-300)/2, 300, 300);
    loading->startLoading(":/res/load.png", 50);

    connect(KeyThread::Get(), &KeyThread::keyEvent, this, &Photo::KeyEvent);
    connect(this, &Photo::finishLoad, this, [&]
    {
        loading->stop(true);
        loading->deleteLater();
        isloading = false;
        update();
    });

    list.clear();

    std::thread([&]{
        QProcess p;
        QString path = QString(PATH VIEW_ONE_PATH) +\
                " " + PATH VIEW_TWO_PATH1 +\
                " " + PATH VIEW_TWO_PATH2 +\
                " " + PATH VIEW_FOUR_PATH1 +\
                " " + PATH VIEW_FOUR_PATH2 +\
                " " + PATH VIEW_FOUR_PATH3 +\
                " " + PATH VIEW_FOUR_PATH4;
        p.start("find " + path + "-type f -iname \"*.png\"");
        p.waitForFinished();
        QString data = p.readAll();
        list = data.split("\n", QString::SkipEmptyParts);

        //qDebug() << list;
        emit finishLoad();
    }).detach();
#endif
    setFocusPolicy(Qt::StrongFocus);
    this->setAttribute(Qt::WA_AcceptTouchEvents);

    timer.setInterval(250);
    timer.setSingleShot(true);
}

Photo::~Photo()
{
    emit sigClose();
}

void Photo::paintEvent(QPaintEvent *)
{
#if 1
    QPainter painter(this);
    QBrush b(QColor("#424655"));
    //painter.setBrush(b);
    painter.fillRect(rect(), b);

    if(!isloading)
    {
        if(list.size() <= 0)
        {
            QPen pen = QPen(Qt::red,2);
            QFont f;
            f.setPixelSize(50);
            //f.setBold(true);
            painter.setFont(f);
            QBrush brush = QBrush(Qt::red);

            painter.setPen(pen);
            painter.setBrush(brush);

            QString data = "相册为空，请添加图片!";
            painter.drawText(QRect(0,0, 1024, 600), Qt::AlignHCenter|Qt::AlignVCenter, data);
        }
        else
        {
            QImage img;
            img.load(list.at(index));

            if(!img.isNull())
            {
                img = img.scaled(img.width()*scale, img.height()*scale);
                //if(img.width() <= 1024)
                painter.drawImage(QPoint((width()-img.width())/2, (height()-img.height())/2),img);
                //else
                {

                }
            }
            else
                qDebug() << "null";
        }
    }
#endif
}


void Photo::KeyEvent(Key_t type, int key)
{
    if(isloading)
    {
        qDebug() << "isloading";
        return ;
    }

    qDebug() << "Photo:key=" << key << " type=" << type;


    if(key == 0)
    {
        if(list.size() > 0)
        {
            if(type == KEY_PRESS)
            {
                if(index == 0)
                    index = list.size()-1;
                else index--;
                update();
            }
        }
    }
    else if(key == 1)
    {
        if(list.size() > 0)
        {
            if(type == KEY_PRESS)
            {
                index++;
                index %= list.size();

                update();
            }
        }
    }
    else if(key == 2)
    {
        if(type == KEY_PRESS)
        {
            close();
        }
    }
}

void Photo::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "keyPressEvent";
    if(event->key() == Qt::Key_A)
    {
        KeyEvent(KEY_PRESS, 0);
    }
    else if(event->key() == Qt::Key_D)
    {
        KeyEvent(KEY_PRESS, 1);
    }
    else if(event->key() == Qt::Key_Escape)
    {
        KeyEvent(KEY_PRESS, 2);
    }
}

void Photo::mousePressEvent(QMouseEvent *)
{
    qDebug() << "mousePressEvent";
}

void Photo::mouseMoveEvent(QMouseEvent *)
{
    qDebug() << "mouseMoveEvent";
}

void Photo::mouseReleaseEvent(QMouseEvent *)
{
    qDebug() << "mouseReleaseEvent";
}

bool Photo::event(QEvent *e)
{
    static int index = 0;
    static qreal _lastScaleFactor = 0.0;
    static int move = 0;
    switch (e->type())
    {
        case QEvent::TouchBegin:
        case QEvent::TouchUpdate:
        case QEvent::TouchEnd:
        {
            //qDebug() <<"CProjectionPicture::event"<<e->type();
            QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
            QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
            if (touchPoints.count() == 2)
            {
                //缩放
                const QTouchEvent::TouchPoint &touchPoint0 = touchPoints.first();
                const QTouchEvent::TouchPoint &touchPoint1 = touchPoints.last();
                qreal currentScaleFactor = QLineF(touchPoint0.pos(), touchPoint1.pos()).length()
                        / QLineF(touchPoint0.startPos(), touchPoint1.startPos()).length();
                if (currentScaleFactor  > _lastScaleFactor)
                    index++;
                else if (currentScaleFactor  < _lastScaleFactor)
                    index--;
                if (index == 5)//超过5次放大，则认为有效.防抖操作
                {
                    index = 0;
                    //zoomOnce(true);
                    if(scale < 2.0)
                        scale += 0.1;
                    qDebug() << "big";
                }
                else if (index == -5)
                {
                    index = 0;
                    //zoomOnce(false);
                    qDebug() << "small";
                    if(scale > 0.5)
                        scale -= 0.1;
                }
                //qDebug()<<index<<currentScaleFactor<<_lastScaleFactor;
                _lastScaleFactor = currentScaleFactor;
                timer.start();
                update();
            }
            else if (touchPoints.count() == 1)
            {
                const QTouchEvent::TouchPoint &touchPoint0 = touchPoints.first();
                const auto& pos = touchPoint0.pos();
                const auto& posLast = touchPoint0.lastPos();
                const auto& posDelta = pos - posLast;
                auto dx = int(posDelta.x());
                //auto dy = int(posDelta.y());
                if(abs(dx) >= 30 && !timer.isActive())//|| dy != 0
                {
                    /// 有效的平移系数（delta值）
                    /// 使用dx和dy进行位置平移
                    qDebug() << "move";
                    move = dx;
                }
            }
            if (touchEvent->touchPointStates() & Qt::TouchPointReleased)
            {
                //qDebug()<<"Qt::TouchPointReleased:" << move;
                if(move > 0)
                {
                    scale = 1.0;
                    KeyEvent(KEY_PRESS, 0);
                }
                else if(move < 0)
                {
                    scale = 1.0;
                    KeyEvent(KEY_PRESS, 1);
                }
                move = 0;
            }
            return true;
        }
        default:
            break;
    }

    return QWidget::event(e);
}
